package user;

import Dao.communityDao;
import Dao.communityDaoImpl;
import been.Announcements;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(value = "/addAnnouncement")
public class addAnnouncementServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        communityDao dao = new communityDaoImpl();
        Announcements announcements = null;
        String message =null;

        int announcement_id = 0;
        String announcement_idParam = request.getParameter("announcement_id");
        if (announcement_idParam != null) {
            try{
                announcement_id = Integer.parseInt(announcement_idParam);
            } catch (NumberFormatException e) {
               e.printStackTrace();
            }
        }
        else {
            message="id不能为空";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/WEB-INF/user/addAnnouncement.jsp").forward(request, response);
            return;
        }

        String title=request.getParameter("title");
        if (title == null||title.isEmpty()) {
            message="标题不能为空";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/WEB-INF/user/addAnnouncement.jsp").forward(request, response);
        }

        String content=request.getParameter("content");
        if (content == null||content.isEmpty()) {
            message="内容不能为空";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/WEB-INF/user/addAnnouncement.jsp").forward(request, response);
        }

        try{
            announcements = new Announcements(announcement_id,title,content);
            int res=dao.addAnnouncement(announcements);
            if (res > 0) {
                message="发布成功";
                request.setAttribute("message", message);
                request.getRequestDispatcher("/WEB-INF/user/addAnnouncement.jsp").forward(request, response);
            }
            else {
                message="发布失败";
                request.setAttribute("message", message);
                request.getRequestDispatcher("/WEB-INF/user/addAnnouncement.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
